package com.daocao.hua.activity;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.impl.BankInfoImpl;
import com.daocao.hua.model.BankModel;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.CircularProgress;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.V19FrameLayout;

import java.lang.ref.SoftReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 2017/9/20.
 */

public class BankEditV2Activity extends BaseActivity {
    @BindView(R.id.img_bank_bg)
    ImageView imgBankBg;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.layout_back)
    V19FrameLayout layoutBack;
    @BindView(R.id.img_bank_icon)
    ImageView imgBankIcon;
    @BindView(R.id.fl_bank_icon)
    FrameLayout flBankIcon;
    @BindView(R.id.txt_type_bank)
    TextView txtTypeBank;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.btn_name)
    ImageView btnName;
    @BindView(R.id.edit_num)
    EditText editNum;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.btn_phone)
    ImageView btnPhone;
    @BindView(R.id.edit_send_code)
    EditText editSendCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.layout_send_code)
    LinearLayout layoutSendCode;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private static final int SEND_CODE = 0;
    private static final int AUTH = 1;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    private Unbinder unbinder;
    private int[] bankImg = {R.mipmap.bank_default, R.mipmap.guangfa, R.mipmap.huaxia, R.mipmap.shanghai, R.mipmap.xingye, R.mipmap.zhaoshang, R.mipmap.gongshang, R.mipmap.nongye, R.mipmap.zhongguoyinhang, R.mipmap.zhongxin, R.mipmap.minsheng, R.mipmap.jianshe, R.mipmap.guangda, R.mipmap.pufa, R.mipmap.youzheng, R.mipmap.nongcun, R.mipmap.jiaotong};
    private String bank_id;
    private String realName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bank_edit_v2_activity);
        unbinder = ButterKnife.bind(this);
        initBar();
        init();
    }

    private void init() {
        Util.bankCardNumAddSpace(editNum);
        editNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                pretime = System.currentTimeMillis();
                if (!hasTimeDown) starTime();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        realName = getIntent().getStringExtra("realName");
        editName.setText(realName);
    }


    private void getBankImg(String bankName) {
        try {
            imgBankIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext().getApplicationContext(), bankImg[0]));
            if (TextUtils.isEmpty(bankName)) return;
            int id = 0;
            if (bankName.contains(getApplicationContext().getString(R.string.guangfa))) id = 1;
            if (bankName.contains(getApplicationContext().getString(R.string.huaxia))) id = 2;
            if (bankName.contains(getApplicationContext().getString(R.string.shanghai))) id = 3;
            if (bankName.contains(getApplicationContext().getString(R.string.xingye))) id = 4;
            if (bankName.contains(getApplicationContext().getString(R.string.zhaoshang))) id = 5;
            if (bankName.contains(getApplicationContext().getString(R.string.gongshang))) id = 6;
            if (bankName.contains(getApplicationContext().getString(R.string.nongye))) id = 7;
            if (bankName.contains(getApplicationContext().getString(R.string.zhongguoyinhang)))
                id = 8;
            if (bankName.contains(getApplicationContext().getString(R.string.zhongxin))) id = 9;
            if (bankName.contains(getApplicationContext().getString(R.string.minsheng))) id = 10;
            if (bankName.contains(getApplicationContext().getString(R.string.jianshe))) id = 11;
            if (bankName.contains(getApplicationContext().getString(R.string.guangda))) id = 12;
            if (bankName.contains(getApplicationContext().getString(R.string.pufa))) id = 13;
            if (bankName.contains(getApplicationContext().getString(R.string.youzheng))) id = 14;
            if (bankName.contains(getApplicationContext().getString(R.string.nongcun))) id = 15;
            if (bankName.contains(getApplicationContext().getString(R.string.jiaotong))) id = 16;

            imgBankIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext().getApplicationContext(), bankImg[id]));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据卡号获取信息
     */
    private void getBankCardNo() {
        new BankInfoImpl().getBankCardno(getApplicationContext(), editNum.getText().toString().trim().replace(" ", ""), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                BankModel model = (BankModel) o;
                txtTypeBank.setText(model.getName());
                bank_id = model.getId();
                getBankImg(model.getName());

            }

            @Override
            public void onFailure(String cause) {
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private TimeHandler mHandler = new TimeHandler();

    private final class TimeHandler extends Handler {
        private final SoftReference<BankEditV2Activity> softBitmap;
        private BankEditV2Activity activity;


        public TimeHandler() {
            softBitmap = new SoftReference<BankEditV2Activity>(BankEditV2Activity.this);
            activity = softBitmap.get();
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activity == null) {
                activity = softBitmap.get();
            }
            activity.starTime();
        }
    }

    private long pretime = 0;
    private boolean hasTimeDown = false;

    /**
     * 检测银行卡
     */
    private void starTime() {
        hasTimeDown = true;
        if (System.currentTimeMillis() - pretime > 1000) {
            hasTimeDown = false;
            getBankCardNo();
        } else {
            mHandler.sendEmptyMessageDelayed(1, 200);
        }
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(editNum.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.bank_id_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.phone_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private boolean checkCode() {
        if (TextUtils.isEmpty(editSendCode.getText().toString().trim())) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.code_is_empty), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) mHandler.removeCallbacks(null);
        if (timer != null) timer.cancel();
        unbinder.unbind();
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };
    private boolean isSend;


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        if (isSend)
            btnSendCode.setText(getResources().getString(R.string.send_code_again));
        else
            btnSendCode.setText(getResources().getString(R.string.get_code));
        btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.blue));
    }


    private void showLoading(boolean b) {
        if (b) {
            if (loading != null) loading.setVisibility(View.VISIBLE);
        } else {
            if (loading != null) loading.setVisibility(View.GONE);
        }
    }

    /**
     * 获取银行卡鉴权信息
     */
    private void getAuthInfo(final int type, String bankcard, String mobile, String code) {
        showLoading(true);
        new BankInfoImpl().getAuthInfo(getApplicationContext(), bankcard, mobile, code, new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
                try {
                    showLoading(false);
                    isSend = true;
                    if (type > 0) {
                        finish();
                        ToastUtil.makeText(getApplicationContext(), "绑定银行卡成功", Toast.LENGTH_SHORT).show();
                    } else {
                        ToastUtil.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_SHORT).show();
                    }

                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String cause) {
                ToastUtil.makeText(getApplicationContext(), cause, Toast.LENGTH_SHORT).show();
                showLoading(false);
                resetBtn();
            }
        });
    }


    @OnClick({R.id.btn_back, R.id.btn_name, R.id.btn_phone, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_name:
                showDialog(getResources().getString(R.string.bank_dialog_title1), getResources().getString(R.string.bank_dialog_content1));
                break;
            case R.id.btn_phone:
                showDialog(getResources().getString(R.string.bank_dialog_title1), getResources().getString(R.string.bank_dialog_content2));
                break;
            case R.id.btn_send_code:
                if(checkInput()){
                    timer.start();
                    getAuthInfo(SEND_CODE, editNum.getText().toString().trim().replace(" ", ""), editPhone.getText().toString().trim(), "");
                }
                break;
            case R.id.btn_submit:
                if(checkInput()&&checkCode()){
                    getAuthInfo(AUTH, editNum.getText().toString().trim().replace(" ", ""), editPhone.getText().toString().trim(), editSendCode.getText().toString().trim());
                }
                break;
        }
    }

    private void showDialog(String title, String content) {
        Dialog.showDefaultDialog(this, title, content, "", getResources().getString(R.string.ok), false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {

            }
        });
    }
}
